﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace com.huawei.esdk.tp.professional.Utils
{
    public abstract class Encrypt
    {
        public static string getEncryptPassword(String randomkey, String key)
        {
            if (StringUtils.isNullOrEmpty(key) || StringUtils.isNullOrEmpty(randomkey))
            {
                return null;
            }
            byte[] encryptPassword;
            // SHA256加密
            System.Security.Cryptography.SHA256 s256 = new SHA256Managed();
            encryptPassword = s256.ComputeHash(ASCIIEncoding.Default.GetBytes(key));

            // 创建一个新的Stringbuilder来保存字节，并且创建一个字符串。
            StringBuilder sBuilder = new StringBuilder();

            // 循环哈希值的每一个字节，并以十六进制格式保存为字符串
            for (int i = 0; i < encryptPassword.Length; i++)
            {
                sBuilder.Append(encryptPassword[i].ToString("x2"));
            }
            string password = sBuilder.ToString();

            sBuilder = new StringBuilder();

            byte[] random = Base64Utils.getFromBASE64(randomkey);
            for (int i = 0; i < random.Length; i++)
            {
                sBuilder.Append(random[i].ToString("x2"));
            }
            password += sBuilder.ToString();

            encryptPassword = s256.ComputeHash( ASCIIEncoding.Default.GetBytes(password));
            s256.Clear();

            for (int i = 0; i < encryptPassword.Length; i++)
            {
                sBuilder.Append(encryptPassword[i].ToString("x2"));
            }
            string ep = Base64Utils.encode(encryptPassword);
            return ep;
        }
    }
}
